borderless 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,275 @@
1
+ """International visa pathway heuristics for researchers.
2
+
3
+ Given the same profile evidence used for US evaluation, scores likely fit
4
+ for skilled-migration and talent visas in other countries. Nuanced country-
5
+ specific advice is delegated to the LLM --review step.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from datetime import date
12
+
13
+ from .criteria import Strength
14
+ from .profile_loader import completed_education
15
+
16
+ # ISO-style codes → display names. Used by CLI --country flag.
17
+ COUNTRY_NAMES: dict[str, str] = {
18
+ "us": "United States",
19
+ "au": "Australia",
20
+ "nz": "New Zealand",
21
+ "uk": "United Kingdom",
22
+ "ca": "Canada",
23
+ "de": "Germany",
24
+ "nl": "Netherlands",
25
+ "fr": "France",
26
+ "it": "Italy",
27
+ "gr": "Greece",
28
+ "ae": "United Arab Emirates",
29
+ "sg": "Singapore",
30
+ "kr": "South Korea",
31
+ "ch": "Switzerland",
32
+ "jp": "Japan",
33
+ "mx": "Mexico"
34
+ }
35
+
36
+ # Aliases accepted by --country (e.g. "dubai" → "ae")
37
+ COUNTRY_ALIASES: dict[str, str] = {
38
+ "usa": "us",
39
+ "america": "us",
40
+ "united states": "us",
41
+ "britain": "uk",
42
+ "england": "uk",
43
+ "uae": "ae",
44
+ "dubai": "ae",
45
+ "emirates": "ae",
46
+ "korea": "kr",
47
+ "south korea": "kr",
48
+ "holland": "nl",
49
+ "netherlands": "nl",
50
+ "switzerland": "ch",
51
+ "japan": "jp",
52
+ "greece": "gr",
53
+ "italy": "it",
54
+ "france": "fr",
55
+ "germany": "de",
56
+ "australia": "au",
57
+ "canada": "ca",
58
+ "singapore": "sg",
59
+ "mexico": "mx"
60
+ }
61
+
62
+
63
+ def resolve_country(value: str | None) -> str | None:
64
+ """Normalize a --country value to a canonical country code."""
65
+ if value is None:
66
+ return None
67
+ key = value.strip().lower()
68
+ if key in COUNTRY_NAMES:
69
+ return key
70
+ if key in COUNTRY_ALIASES:
71
+ return COUNTRY_ALIASES[key]
72
+ raise ValueError(
73
+ f"Unknown country {value!r}. "
74
+ f"Choose from: {', '.join(sorted(COUNTRY_NAMES))} "
75
+ f"(aliases: {', '.join(sorted(COUNTRY_ALIASES))})"
76
+ )
77
+
78
+
79
+ @dataclass
80
+ class IntlPathway:
81
+ """A single international visa pathway assessment."""
82
+
83
+ country_code: str
84
+ country: str
85
+ pathway: str
86
+ visa_type: str # "permanent", "temporary", or "bridge"
87
+ strength: Strength
88
+ evidence: list[str]
89
+ notes: str = ""
90
+
91
+
92
+ def _pub_count(profile: dict) -> int:
93
+ return sum(
94
+ 1 for pub in profile.get("publications") or []
95
+ if isinstance(pub, dict) and pub.get("peer_reviewed") is True
96
+ )
97
+
98
+
99
+ def _citations(profile: dict) -> int:
100
+ metrics = profile.get("metrics") or {}
101
+ if metrics.get("total_citations") is not None:
102
+ return int(metrics["total_citations"])
103
+ pubs = profile.get("publications") or []
104
+ return sum(int(p.get("citations") or 0) for p in pubs if isinstance(p, dict))
105
+
106
+
107
+ def _has_phd(education: list[dict]) -> bool:
108
+ for edu in education:
109
+ degree = (edu.get("degree") or "").lower()
110
+ if "phd" in degree or "doctor" in degree:
111
+ return True
112
+ return False
113
+
114
+
115
+ def _review_count(profile: dict) -> int:
116
+ return len(profile.get("reviewing") or [])
117
+
118
+
119
+ def _is_stem_field(profile: dict) -> bool:
120
+ field = (profile.get("field") or "").lower()
121
+ keywords = (
122
+ "computer", "machine learning", "artificial intelligence", "nlp",
123
+ "data science", "engineering", "science", "research", "robotics",
124
+ )
125
+ return any(k in field for k in keywords)
126
+
127
+
128
+ def _talent_score(
129
+ pubs: int, cites: int, reviews: int, phd: bool, us_met: int, us_strong: int,
130
+ ) -> tuple[Strength, list[str]]:
131
+ """Shared signal for talent-style visas."""
132
+ evidence: list[str] = []
133
+
134
+ if phd:
135
+ evidence.append("Completed doctorate")
136
+ if pubs:
137
+ evidence.append(f"{pubs} peer-reviewed publications")
138
+ if cites:
139
+ evidence.append(f"{cites} citations")
140
+ if reviews:
141
+ evidence.append(f"Reviewer for {reviews} venues")
142
+ if us_met:
143
+ evidence.append(f"US extraordinary-ability criteria at moderate+: {us_met}/10")
144
+
145
+ if us_met >= 3 and us_strong >= 1:
146
+ return Strength.STRONG, evidence
147
+ if (phd and pubs >= 3) or (pubs >= 4 and cites >= 20) or us_met >= 2:
148
+ return Strength.MODERATE, evidence
149
+ if phd or pubs >= 2:
150
+ return Strength.WEAK, evidence
151
+ return Strength.NOT_MET, evidence
152
+
153
+
154
+ def _pathway(
155
+ code: str,
156
+ pathway: str,
157
+ visa_type: str,
158
+ strength: Strength,
159
+ evidence: list[str],
160
+ notes: str,
161
+ ) -> IntlPathway:
162
+ if visa_type != "permanent":
163
+ notes += " Initial grant is not permanent residence; later settlement has separate requirements."
164
+ return IntlPathway(
165
+ country_code=code,
166
+ country=COUNTRY_NAMES[code],
167
+ pathway=pathway,
168
+ visa_type=visa_type,
169
+ strength=strength,
170
+ evidence=evidence,
171
+ notes=notes,
172
+ )
173
+
174
+
175
+ # Pathway metadata is separate from shared, directional scoring rules.
176
+ # Tuple fields: name, initial residence type, scoring rule, requirements.
177
+ _PATHWAYS = {
178
+ "au": (("National Innovation (subclass 858)", "permanent", "talent",
179
+ "Invitation following an EOI and eligible Form 1000 nomination required; fit is not application eligibility. "
180
+ "Source: https://immi.homeaffairs.gov.au/visas/getting-a-visa/visa-listing/national-innovation-visa-858"),),
181
+ "nz": (("Skilled Migrant / Green List", "permanent", "stem",
182
+ "Points-based SMC or job on Green List; smaller market than AU/CA."),),
183
+ "uk": (("Global Talent Visa", "temporary", "talent",
184
+ "Endorsement from approved body (e.g., UKRI, Royal Society, Tech Nation successor)."),),
185
+ "ca": (
186
+ ("Express Entry", "permanent", "canada",
187
+ "Qualifying work experience, language scores and competitive CRS required."),
188
+ ("Global Talent Stream", "temporary", "canada",
189
+ "Qualifying employer and work-permit application required."),
190
+ ),
191
+ "de": (
192
+ ("EU Blue Card", "temporary", "blue_card",
193
+ "Recognized qualifications, qualifying job offer and salary threshold required."),
194
+ ("Opportunity Card (Chancenkarte)", "bridge", "blue_card",
195
+ "Qualification or points route, funding and other job-search requirements apply."),
196
+ ),
197
+ "nl": (
198
+ ("Highly Skilled Migrant", "temporary", "worker", "Recognized sponsor and salary threshold required."),
199
+ ("Orientation Year", "bridge", "recent",
200
+ "Qualifying graduation/research within three years required; foreign-degree institution, "
201
+ "ranking, language and diploma-evaluation conditions must be verified. "
202
+ "Source: https://ind.nl/en/residence-permits/work/residence-permit-for-orientation-year"),
203
+ ),
204
+ "fr": (("Passeport Talent (Chercheur) / EU Blue Card", "temporary", "talent",
205
+ "4-year renewable permit for researchers; job contract or hosting agreement required."),),
206
+ "it": (("EU Blue Card / Permesso di Soggiorno per Lavoro", "temporary", "papers2",
207
+ "Employer-sponsored; EU Blue Card for salary threshold + degree recognition."),),
208
+ "gr": (("EU Blue Card / Researcher Residence Permit", "temporary", "papers3",
209
+ "Employer or research institution sponsorship; EU Blue Card for qualified roles."),),
210
+ "ae": (("Golden Visa (Scientists/Talents) / Employment Visa", "temporary", "golden",
211
+ "10-year Golden Visa for scientists/researchers; standard route is employer-sponsored work visa."),),
212
+ "sg": (("Employment Pass / Tech.Pass", "temporary", "papers3",
213
+ "Employer-sponsored EP is standard; Tech.Pass for senior tech leaders."),),
214
+ "kr": (("E-7 Professional / F-2 Points Residence", "temporary", "stem",
215
+ "E-7 requires sponsoring employer; F-2 points for long-term residence."),),
216
+ "ch": (("B Permit (Specialists) / L Permit", "temporary", "papers2",
217
+ "Employer must prove no Swiss/EU candidate available; quotas apply for non-EU nationals."),),
218
+ "jp": (("Highly Skilled Professional (HSP) / Engineer Visa", "temporary", "papers3",
219
+ "HSP uses points system (education, salary, research); 70+ points for preferential treatment."),),
220
+ "mx": (("Temporary Resident Visa (Professional) / INM Work Permit", "temporary", "stem",
221
+ "Employer sponsorship required; path to permanent residency after 4 years of temporary status."),),
222
+ }
223
+
224
+
225
+ def _pathway_strength(rule: str, signals: dict, talent: Strength) -> Strength:
226
+ phd, pubs, cites = signals["phd"], signals["pubs"], signals["cites"]
227
+ if rule == "talent":
228
+ return talent
229
+ if rule == "recent":
230
+ return Strength.WEAK if signals["recent"] else Strength.NOT_MET
231
+ if rule == "worker":
232
+ return Strength.MODERATE if phd else Strength.WEAK
233
+ if rule == "canada":
234
+ return Strength.MODERATE if phd else Strength.WEAK if pubs >= 2 else Strength.NOT_MET
235
+ if rule == "blue_card":
236
+ return Strength.MODERATE if phd else Strength.WEAK if signals["stem"] else Strength.NOT_MET
237
+ if rule == "golden":
238
+ return Strength.MODERATE if pubs >= 3 or cites >= 20 else Strength.WEAK if phd else Strength.NOT_MET
239
+ if rule == "stem":
240
+ supported = phd and signals["stem"]
241
+ elif rule == "papers2":
242
+ supported = phd and pubs >= 2
243
+ elif rule == "papers3":
244
+ supported = phd and pubs >= 3
245
+ else:
246
+ raise ValueError(f"Unknown international scoring rule: {rule}")
247
+ return Strength.MODERATE if supported else Strength.WEAK if phd else Strength.NOT_MET
248
+
249
+
250
+ def evaluate_international(
251
+ profile: dict,
252
+ us_met: int = 0,
253
+ us_strong: int = 0,
254
+ country: str | None = None,
255
+ ) -> list[IntlPathway]:
256
+ """Score international pathways, optionally for a single country."""
257
+ education = completed_education(profile)
258
+ pubs, cites, reviews = _pub_count(profile), _citations(profile), _review_count(profile)
259
+ phd = _has_phd(education)
260
+ signals = {
261
+ "phd": phd, "pubs": pubs, "cites": cites, "stem": _is_stem_field(profile),
262
+ # ponytail: year-level recency; use exact graduation/research dates for a precise Dutch assessment.
263
+ "recent": any((e.get("year") or 0) >= date.today().year - 3 for e in education),
264
+ }
265
+ talent, evidence = _talent_score(pubs, cites, reviews, phd, us_met, us_strong)
266
+ if profile.get("field"):
267
+ evidence.append(f"Field: {profile['field']}")
268
+ codes = [country] if country else _PATHWAYS
269
+ results = []
270
+ for code in codes:
271
+ for name, kind, rule, notes in _PATHWAYS.get(code, ()):
272
+ results.append(_pathway(
273
+ code, name, kind, _pathway_strength(rule, signals, talent), evidence.copy(), notes,
274
+ ))
275
+ return results
@@ -0,0 +1,226 @@
1
+ """LLM-powered review of the evaluation report.
2
+
3
+ Sends the structured evaluation to an external LLM (OpenRouter, Anthropic, or OpenAI)
4
+ for a nuanced, immigration-attorney-style analysis.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+
11
+ import yaml
12
+
13
+ from .evaluator import EvaluationReport
14
+ from .intl_visas import COUNTRY_NAMES
15
+ from .policy import visa_availability
16
+
17
+ PROVIDERS = ("openrouter", "anthropic", "openai", "deepseek")
18
+
19
+ SYSTEM_PROMPT = """\
20
+ You are an experienced immigration strategist specializing in global talent mobility \
21
+ for researchers and technologists. You have deep knowledge of:
22
+
23
+ - **US**: EB-1A, EB-1B, EB2-NIW, O-1A (USCIS policy, Kazarian two-step analysis)
24
+ - **International alternatives**: Australia National Innovation (858), UK Global Talent, \
25
+ Canada Express Entry/GTS, Germany EU Blue Card/Chancenkarte, Netherlands HSM, \
26
+ New Zealand Skilled Migrant/Green List, Singapore EP/Tech.Pass, South Korea E-7
27
+
28
+ Given a candidate's profile and structured evaluation report, provide:
29
+
30
+ 1. **Overall assessment** – a candid 2-3 sentence verdict on filing readiness.
31
+ 2. **US strategy** – strongest arguments, critical weaknesses, and filing timeline \
32
+ for EB-1A / EB-1B / NIW / O-1A. Reference USCIS criteria by name.
33
+ 3. **International alternatives** – given increasing US student/work visa uncertainty, \
34
+ rank the top 3 non-US destinations for this profile. For each, name the specific \
35
+ visa pathway, assess likelihood, and note key requirements (endorsement, job offer, \
36
+ points threshold). Cover at least Europe, Australia/NZ, and East Asia where relevant.
37
+ 4. **Strategic recommendations** – 3-5 concrete, prioritized actions across US and \
38
+ international options, with estimated timelines.
39
+ 5. **Recommended path** – single best overall strategy considering US difficulty, \
40
+ India backlog (if applicable), and international mobility.
41
+
42
+ Be specific and honest about weaknesses. Distinguish petition eligibility, adjustment \
43
+ filing availability, and final action. Use the source-dated availability snapshot in \
44
+ the report, never infer chargeability from nationality or predict waits from cutoff \
45
+ dates. Verify current sources before advising. Keep the response concise and actionable.
46
+ """
47
+
48
+
49
+ def _report_to_text(report: EvaluationReport, profile: dict) -> str:
50
+ """Serialize the evaluation report into a text summary for the LLM."""
51
+ lines = [
52
+ f"# Candidate: {report.name}",
53
+ f"Nationality: {report.nationality}",
54
+ f"Field: {profile.get('field', 'N/A')}",
55
+ visa_availability(report.country_of_birth),
56
+ "",
57
+ f"## EB-1A (need 3/10): {report.eb1a_met_count} met, {report.eb1a_strong_count} strong",
58
+ "These are heuristic initial evidence signals, not a final-merits or approval determination.",
59
+ ]
60
+
61
+ for r in report.eb1a_results:
62
+ evidence = "; ".join(r.evidence) if r.evidence else "none"
63
+ lines.append(f" - {r.name}: {r.strength.value} | Evidence: {evidence}")
64
+
65
+ lines.append("")
66
+ lines.append(f"## EB-1B (need 2/6 + employer): {report.eb1b_met_count} criteria met")
67
+ for r in report.eb1b_results:
68
+ evidence = "; ".join(r.evidence) if r.evidence else "none"
69
+ lines.append(f" - {r.name}: {r.strength.value} | Evidence: {evidence}")
70
+
71
+ lines.append("")
72
+ lines.append(f"## EB2-NIW Dhanasar: {'prong signals present' if report.niw_prongs_met else 'gaps remain'}")
73
+ lines.append(f"Overall NIW qualification and prongs supported: {report.niw_signals_supported}; attorney review required")
74
+ for r in report.niw_results:
75
+ evidence = "; ".join(r.evidence) if r.evidence else "none"
76
+ lines.append(f" - {r.name}: {r.strength.value} | Evidence: {evidence}")
77
+
78
+ if report.eb2_base:
79
+ lines.append(f" - EB-2 base qualification: {report.eb2_base.strength.value}")
80
+
81
+ if report.o1a_result:
82
+ lines.append("")
83
+ lines.append(f"## O-1A initial threshold signals (totality unassessed): {report.o1a_result.strength.value}")
84
+ for e in report.o1a_result.evidence:
85
+ lines.append(f" - {e}")
86
+
87
+ if report.intl_results:
88
+ lines.append("")
89
+ lines.append("## International pathways (heuristic)")
90
+ for p in report.intl_results:
91
+ evidence = "; ".join(p.evidence) if p.evidence else "none"
92
+ lines.append(
93
+ f" - {p.country} / {p.pathway} ({p.visa_type}): "
94
+ f"{p.strength.value} | {evidence}"
95
+ )
96
+ if p.notes:
97
+ lines.append(f" Note: {p.notes}")
98
+
99
+ lines.append("")
100
+ lines.append("## Profile YAML")
101
+ lines.append(yaml.dump(profile, default_flow_style=False, sort_keys=False))
102
+
103
+ return "\n".join(lines)
104
+
105
+
106
+ def _call_openai_compatible(
107
+ user_message: str,
108
+ model: str,
109
+ base_url: str | None = None,
110
+ api_key_env: str = "OPENAI_API_KEY",
111
+ extra_body: dict | None = None,
112
+ ) -> str:
113
+ """Call any OpenAI-compatible chat API.
114
+
115
+ Args:
116
+ user_message: The profile report text to review.
117
+ model: Model name.
118
+ base_url: Custom base URL (e.g. OpenRouter). None uses OpenAI default.
119
+ api_key_env: Env var name for the API key.
120
+ extra_body: Provider-specific request options, such as disabling thinking.
121
+ """
122
+ from openai import OpenAI
123
+
124
+ api_key = os.environ.get(api_key_env)
125
+ if not api_key or not api_key.strip():
126
+ raise ValueError(f"Set {api_key_env} before requesting an LLM review")
127
+ client_kwargs: dict = {"api_key": api_key}
128
+ if base_url is not None:
129
+ client_kwargs["base_url"] = base_url
130
+
131
+ client = OpenAI(**client_kwargs)
132
+ response = client.chat.completions.create(
133
+ model=model,
134
+ max_tokens=4096,
135
+ extra_body=extra_body,
136
+ messages=[
137
+ {"role": "system", "content": SYSTEM_PROMPT},
138
+ {"role": "user", "content": user_message},
139
+ ],
140
+ )
141
+ content = response.choices[0].message.content
142
+ if not (content or "").strip():
143
+ raise ValueError(
144
+ f"OpenAI-compatible response ({base_url or 'OpenAI'}) contained no content"
145
+ )
146
+ return content
147
+
148
+
149
+ def _call_anthropic(user_message: str, model: str) -> str:
150
+ from anthropic import Anthropic
151
+
152
+ client = Anthropic()
153
+ response = client.messages.create(
154
+ model=model,
155
+ max_tokens=4096,
156
+ thinking={"type": "disabled"},
157
+ system=SYSTEM_PROMPT,
158
+ messages=[{"role": "user", "content": user_message}],
159
+ )
160
+ text_parts = [block.text for block in response.content if block.type == "text"]
161
+ if not text_parts:
162
+ raise ValueError("Anthropic response contained no text blocks")
163
+ return "\n".join(text_parts)
164
+
165
+
166
+ DEFAULT_MODELS = {
167
+ "openrouter": "deepseek/deepseek-v4-flash",
168
+ "anthropic": "claude-sonnet-5",
169
+ "openai": "gpt-5.3-chat-latest",
170
+ "deepseek": "deepseek-v4-flash",
171
+ }
172
+
173
+
174
+ def llm_review(
175
+ report: EvaluationReport,
176
+ profile: dict,
177
+ provider: str = "openrouter",
178
+ model: str | None = None,
179
+ country: str | None = None,
180
+ ) -> str:
181
+ """Send the evaluation report to an LLM and return its analysis.
182
+
183
+ Args:
184
+ report: The structured evaluation report.
185
+ profile: The raw profile dict from YAML.
186
+ provider: "openrouter", "anthropic", "openai", or "deepseek".
187
+ model: Model name override. Defaults to provider-specific default.
188
+ country: Optional country code to focus the review (e.g. "fr", "us").
189
+
190
+ Returns:
191
+ The LLM's analysis as a string.
192
+ """
193
+ if provider not in PROVIDERS:
194
+ raise ValueError(f"Unknown provider {provider!r}. Choose from {PROVIDERS}")
195
+
196
+ model = model or DEFAULT_MODELS[provider]
197
+ focus = ""
198
+ if country:
199
+ name = COUNTRY_NAMES.get(country, country)
200
+ focus = f"Focus your analysis on {name} visa pathways only.\n\n"
201
+
202
+ user_message = (
203
+ focus
204
+ + "Review this visa eligibility evaluation and provide your analysis:\n\n"
205
+ + _report_to_text(report, profile)
206
+ )
207
+
208
+ if provider == "anthropic":
209
+ return _call_anthropic(user_message, model)
210
+ if provider == "openrouter":
211
+ return _call_openai_compatible(
212
+ user_message,
213
+ model,
214
+ base_url="https://openrouter.ai/api/v1",
215
+ api_key_env="OPENROUTER_API_KEY",
216
+ extra_body={"reasoning": {"enabled": False}},
217
+ )
218
+ if provider == "deepseek":
219
+ return _call_openai_compatible(
220
+ user_message,
221
+ model,
222
+ base_url="https://api.deepseek.com",
223
+ api_key_env="DEEPSEEK_API_KEY",
224
+ extra_body={"thinking": {"type": "disabled"}},
225
+ )
226
+ return _call_openai_compatible(user_message, model)
@@ -0,0 +1,172 @@
1
+ """Generate a markdown evaluation report from profile.yaml."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+
8
+ import click
9
+
10
+ from .cli_options import common_options
11
+ from .criteria import CriterionResult, Strength
12
+ from .evaluator import EvaluationReport, evaluate
13
+ from .policy import visa_availability
14
+ from .profile_loader import load_profile
15
+
16
+ STRENGTH_LABELS = {
17
+ Strength.NOT_MET: "Not Met",
18
+ Strength.WEAK: "Weak",
19
+ Strength.MODERATE: "Moderate",
20
+ Strength.STRONG: "Strong",
21
+ }
22
+
23
+
24
+ def _strength_label(s: Strength) -> str:
25
+ return STRENGTH_LABELS[s]
26
+
27
+
28
+ def _criteria_section(title: str, results: list[CriterionResult], numbered: bool = False) -> list[str]:
29
+ lines = [f"## {title}", ""]
30
+ lines.append("| Criterion | Strength | Evidence |")
31
+ lines.append("| --- | --- | --- |")
32
+ for i, r in enumerate(results, 1):
33
+ name = f"{i}. {r.name}" if numbered else r.name
34
+ evidence = "; ".join(r.evidence) if r.evidence else "—"
35
+ evidence = evidence.replace("|", "\\|").replace("\n", " ")
36
+ lines.append(f"| {name} | {_strength_label(r.strength)} | {evidence} |")
37
+ lines.append("")
38
+ return lines
39
+
40
+
41
+ def report_to_markdown(report: EvaluationReport, llm_review: str | None = None) -> str:
42
+ """Serialize an evaluation report to markdown."""
43
+ now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
44
+ lines = [
45
+ f"# Visa Eligibility Report — {report.name}",
46
+ "",
47
+ f"**Generated:** {now} ",
48
+ f"**Nationality:** {report.nationality} ",
49
+ "",
50
+ "## Summary",
51
+ "",
52
+ "| Category | Status |",
53
+ "| --- | --- |",
54
+ f"| EB-1A | {'Threshold signals; final merits pending' if report.eb1a_threshold_met else 'Strengthen evidence'} "
55
+ f"({report.eb1a_met_count}/3 criteria, {report.eb1a_strong_count} strong) |",
56
+ f"| EB-1B | {'Prerequisites supported; recognition review pending' if report.eb1b_prerequisites_met else 'Gaps remain'} "
57
+ f"({report.eb1b_met_count}/2 criteria) |",
58
+ f"| EB2-NIW | {'Qualification and prong signals present; review required' if report.niw_signals_supported else 'Assess base qualification and prongs'} |",
59
+ ]
60
+
61
+ if report.o1a_result:
62
+ lines.append(
63
+ f"| O-1A | {'Threshold signals; totality pending' if report.o1a_result.strength == Strength.MODERATE else 'Build evidence'} |"
64
+ )
65
+ lines.append("")
66
+
67
+ lines.extend(_criteria_section(
68
+ "EB-1A Extraordinary Ability (need ≥ 3 of 10)",
69
+ report.eb1a_results,
70
+ numbered=True,
71
+ ))
72
+ lines.extend(_criteria_section(
73
+ "EB-1B Outstanding Professor/Researcher (need ≥ 2 of 6 + employer)",
74
+ report.eb1b_results,
75
+ ))
76
+ lines.extend(_criteria_section(
77
+ "EB2-NIW Dhanasar 3-prong test",
78
+ report.niw_results,
79
+ ))
80
+
81
+ if report.eb2_base:
82
+ lines.extend([
83
+ f"**EB-2 base qualification:** {_strength_label(report.eb2_base.strength)}",
84
+ "",
85
+ ])
86
+
87
+ if report.o1a_result:
88
+ r = report.o1a_result
89
+ lines.extend([
90
+ "## O-1A Extraordinary Ability (bridge strategy)",
91
+ "",
92
+ f"**Overall:** {_strength_label(r.strength)}",
93
+ "",
94
+ ])
95
+ for e in r.evidence:
96
+ lines.append(f"- {e}")
97
+ lines.append("")
98
+
99
+ if report.intl_results:
100
+ lines.extend([
101
+ "## International Pathways",
102
+ "",
103
+ "| Code | Country | Pathway | Type | Fit |",
104
+ "| --- | --- | --- | --- | --- |",
105
+ ])
106
+ for p in report.intl_results:
107
+ lines.append(
108
+ f"| {p.country_code} | {p.country} | {p.pathway} | {p.visa_type} "
109
+ f"| {_strength_label(p.strength)} |"
110
+ )
111
+ lines.append("")
112
+ for p in report.intl_results:
113
+ if p.evidence or p.notes:
114
+ lines.append(f"### {p.country} ({p.country_code})")
115
+ lines.append("")
116
+ for e in p.evidence:
117
+ lines.append(f"- {e}")
118
+ if p.notes:
119
+ lines.append(f"- *{p.notes}*")
120
+ lines.append("")
121
+
122
+ lines.extend([
123
+ "## US Visa Availability",
124
+ "",
125
+ visa_availability(report.country_of_birth),
126
+ "",
127
+ ])
128
+
129
+ if llm_review:
130
+ lines.extend([
131
+ "## LLM Review",
132
+ "",
133
+ llm_review.strip(),
134
+ "",
135
+ ])
136
+
137
+ lines.append("---")
138
+ lines.append("*Auto-generated by borderless.*")
139
+ lines.append("")
140
+ return "\n".join(lines)
141
+
142
+
143
+ @click.command()
144
+ @common_options
145
+ @click.option("-o", "--output", required=True, type=click.Path(),
146
+ help="Output markdown file path.")
147
+ def main(profile: str, output: str, review: bool, provider: str, model: str | None) -> None:
148
+ """Generate a markdown visa eligibility report."""
149
+ try:
150
+ data = load_profile(Path(profile))
151
+ report = evaluate(data)
152
+ except (ValueError, OSError) as exc:
153
+ raise click.ClickException(str(exc)) from exc
154
+
155
+ llm_text = None
156
+ if review:
157
+ from .llm_review import llm_review
158
+
159
+ try:
160
+ llm_text = llm_review(report, data, provider=provider, model=model)
161
+ except ValueError as exc:
162
+ raise click.ClickException(str(exc)) from exc
163
+
164
+ md = report_to_markdown(report, llm_review=llm_text)
165
+ out = Path(output)
166
+ out.parent.mkdir(parents=True, exist_ok=True)
167
+ out.write_text(md, encoding="utf-8")
168
+ click.echo(f"Wrote {out}")
169
+
170
+
171
+ if __name__ == "__main__":
172
+ main()